package replication;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import javax.swing.JOptionPane;
import rmi.Server;

public class RegServer_Replication {
	Registry registryPrimaryIp = null;
	Registry registrySecondaryIp = null;
	String hostName;

	public RegServer_Replication(String hostName) {

		String primaryIp = "127.0.0.1";
		String secondaryIp = "127.0.0.1";

		try {
			registryPrimaryIp = LocateRegistry.getRegistry(primaryIp);
			registrySecondaryIp = LocateRegistry.getRegistry(secondaryIp);
		}
		catch(Exception e) {
			System.out.println ("Unable to lookup registry. System exiting");
		}
	}

	public Server getPrimaryServer () {

		Server svr = null;
		Registry reg = getWorkingRegistry();
		if (reg == null) {
			return null;
		}

		try {
			svr = (Server) reg.lookup("TecBox_PrimaryServer");
		} catch (Exception e) {}
		return svr;
	}

	public Server getBackupServer () {

		Server svr = null;
		Registry reg = getWorkingRegistry();
		if (reg == null) {
			return null;
		}

		try {
			svr = (Server) reg.lookup("TecBox_BackupServer");
		} catch (Exception e) {}
		return svr;
	}

	private Registry getWorkingRegistry() {

		Registry reg = null;

		try {
			registryPrimaryIp.lookup("TecBox_PrimaryServer");
			reg = registryPrimaryIp;
		} catch (Exception e) {
			try {
				registrySecondaryIp.lookup("TecBox_PrimaryServer");
				reg = registrySecondaryIp;
			} catch (Exception e1) {
				System.out.println("Both the registries are down. System exiting");
			} 
		} 

		return reg;
	}

	public void shutDown() {
		JOptionPane popUp = new JOptionPane();
		popUp.showMessageDialog(null,
				"TecBox System is experiencing some techinical problems. Please try again later",
				"Fatal error",
				JOptionPane.ERROR_MESSAGE);
		System.exit(-1);
		return;
	}
}
